﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Project.Core.Api.Controllers.Authorize.Dto;
using Project.Core.Common;
using Project.Core.IServices.System;
using Project.Core.Token.Token;

namespace Project.Core.Api.Controllers.Authorize
{
    /// <summary>
    /// 授权Controller
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorizeController : Controller
    {
        private readonly IUserService _userService;
        private JwtSettings _jwtSettings;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userService"></param>
        /// <param name="_jwtSettingsAccesser"></param>
        public AuthorizeController(IUserService userService, IOptions<JwtSettings> _jwtSettingsAccesser)
        {
            _userService = userService;
            _jwtSettings = _jwtSettingsAccesser.Value;
        }

        /// <summary>
        /// 登录获取Token 
        /// </summary>
        /// <param name="Dto"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("Token")]
        public async Task<IActionResult> Token([FromBody]LoginDto Dto)
        {
            if (ModelState.IsValid)//判断是否合法
            {
                var pw = Utils.MD5(Dto.PassWord);
                var Entity = await _userService.Find(x => x.UserName == Dto.UserName && x.PassWord == pw && x.IsValid);
                // var Entity = await _userService.Find(x => x.UserName == Dto.UserName && x.PassWord == Dto.PassWord && x.IsValid);
                if (Entity == null)
                {
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "帐号或密码错误!",
                        Success = false,
                        Total = 0
                    });
                }

                var claim = new Claim[]{
                    new Claim(ClaimTypes.Name, Entity.UserName),
                    new Claim(ClaimTypes.Role, Entity.RoleID.ToString())
                };

                //对称秘钥
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
                //签名证书(秘钥，加密算法)
                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

                //生成token  [注意]需要nuget添加Microsoft.AspNetCore.Authentication.JwtBearer包，并引用System.IdentityModel.Tokens.Jwt命名空间
                var token = new JwtSecurityToken(_jwtSettings.Issuer, _jwtSettings.Audience, claim, DateTime.Now, DateTime.Now.AddMinutes(30), creds);

                return Ok(new ReturnMsg
                {
                    Data = new UserTokenInfo()
                    {
                        UserName = Dto.UserName,
                        Token = new JwtSecurityTokenHandler().WriteToken(token),
                        RoleID = Entity.RoleID,
                        OrganizationID = Entity.OrganizationID,
                        Id = Entity.Id
                    },
                    Msg = "成功",
                    Success = true,
                    Total = 0
                });

            }
            else
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "参数错误",
                    Success = false,
                    Total = 0
                });
            }
        }
    }
}